package net.openadventure.pathfinding;

import util.Point;

public class GridNode implements Comparable<GridNode> {

	private int g;
	private int h;
	
	private int x;
	private int y;
	
	private int targetX;
	private int targetY;
	
	private GridNode parent;
	
	private int gridCol;
	private int gridRow;
	
	public GridNode(int x, int y, GridNode parent, int targetX, int targetY, int gridCol, int gridRow) {
		this.x = x;
		this.y = y;
		this.targetX = targetX;
		this.targetY = targetY;
		this.gridCol = gridCol;
		this.gridRow = gridRow;
		setParent(parent);
		setManhattenH(targetX, targetY);
	}
	
	private void setParent(GridNode parent) {
		this.parent = parent;
		
		if(parent != null) {
			int work;
			if(parent.getX() != x && parent.getY() != y) {
				work = 7;
			} else {
				work = 5;
			}
	
			g = parent.getG() + work;
		} else {
			g = 0;
		}
	}
	
	public GridNode getParent() {
		return parent;
	}
	
	public int getX() {
		return x;
	}
	
	public int getY() {
		return y;
	}
	
	public int getG() {
		return g;
	}
	
	private int getH() {
		return h;
	}
	
	public int getF() {
		return getG() + getH();
	}
	
	private void setManhattenH(int targetX, int targetY) {
		h = 10 * (Math.abs(targetX - x) + Math.abs(targetY - y));
	}

	public int compareTo(GridNode otherNode) {
		return getF() - otherNode.getF();
	}

	@Override
	public boolean equals(Object obj) {
		if(!(obj instanceof GridNode)) return false;
		
		GridNode other = (GridNode)obj;
		if(other.getX() == getX() && other.getY() == getY()) {
			return true;
		}
		
		return false;
	}

	@Override
	public String toString() {
		return "GridNode[x=" + getX() + ",y=" + getY() + ",g=" + getG() + ",h=" + getH() + ",f=" + getF() + ",targX=" + targetX + ",targY=" + targetY + "]";
	}

	public int getGridCol() {
		return gridCol;
	}

	public int getGridRow() {
		return gridRow;
	}
	
	public Point getPoint() {
		return new Point(x,y);
	}
}
